package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @Author: wenjingyuan
 * @Date: 2023/03/19/12:52
 * @Description:用户注册
 */
@WebServlet("/reg")
public class RegServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        //1.从前端得到参数
        String username=req.getParameter("username");
        String nickname=req.getParameter("nickname");
        String password=req.getParameter("password");
        int data=0;
        String msg="未知参数";
        //1.1非空校验
        if(!StrUtil.isBlank(username)&&
                !StrUtil.isBlank(username)&&
                !StrUtil.isBlank(username)) {
            //2.将数据保存到数据库中
            //2.1得到连接
            Connection connection = DBUtils.getConnection();
            //2.2 先判断登录名的唯一性
            String selSql = "select * from userinfo where username=?";
            PreparedStatement statement = connection.prepareStatement(selSql);
            statement.setString(1, username);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                //用户名已存在
                msg="您输入的用户名已经存在，请重新输入！";
            } else { //2.2拼接SQL，得到执行器
                String sql = "insert into userinfo(username,nickname,password) values(?,?,?)";
                statement = connection.prepareStatement(sql);
                //2.3给执行器填充属性
                statement.setString(1, username);
                statement.setString(2, nickname);
                statement.setString(3, SecureUtil.md5(password));
                data = statement.executeUpdate();
            }
            //2.4关闭资源
            DBUtils.close(resultSet, statement, connection);
        }else{
            msg="非法参数";
        }
        //3.将数据库返回的结果响应给前端
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,data,msg)));
    }
}
